package com.luo.sc.oidc.authserver.handler.login;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * 通用登录 - 认证管理器
 *
 * @author luohq
 * @version 1.0.0
 * @date 2022-03-03、
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider
 */
public class UniLoginAuthenticationProvider implements AuthenticationProvider {

    private UniLoginUserDetailsService uniLoginUserDetailsService;

    public UniLoginAuthenticationProvider(UniLoginUserDetailsService uniLoginUserDetailsService) {
        this.uniLoginUserDetailsService = uniLoginUserDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UniLoginAuthenticationToken uniLoginAuthenticationToken = (UniLoginAuthenticationToken) authentication;
        /** 根据认证表单参数查询用户信息 */
        UniLoginUserDetails userDetails = this.uniLoginUserDetailsService.loadUserByAuthParams(uniLoginAuthenticationToken.getAuthParams());
        /** 验证用户信息 */
        this.uniLoginUserDetailsService.authenticateUser(uniLoginAuthenticationToken.getAuthParams(), userDetails);
        /** 构建验证成功结果 */
        UniLoginAuthenticationToken authResult = new UniLoginAuthenticationToken(userDetails, userDetails.getPassword(),
                userDetails.getAuthorities(), uniLoginAuthenticationToken.getAuthParams());
        //移除authParams，避免在session中可以看见密码等信息
        uniLoginAuthenticationToken.setAuthParams(null);
        return authResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //支持对UniLoginAuthenticationToken进行认证
        return (UniLoginAuthenticationToken.class.isAssignableFrom(authentication));
    }
}